package plgnet

import (
	"dgo/MyProj/PrjHttpUtils"
	"dgo/MyProj/PrjHttpWs"
	"dgo/goutils/gohttp"
	"dgo/goutils/utils"
	"fmt"
	"gitee.com/ymofen/supervalue"
)

type PlgHttpWsServ struct {
	wsservice *PrjHttpWs.WsHttpService
	plugId    string
	wsurl     string
	conf      *wrapper.SuperValue

	monitor_send *utils.MonitorSpeedSizeRec
	monitor_recv *utils.MonitorSpeedSizeRec
}

func (this *PlgHttpWsServ) SetPlugID(val string) {
	this.plugId = val
}

/*
*
//

	和cmd-addr端口一致
	wssvr转发服务

	{
	   "wsurl":"/ws/service"
	}
*/
func (this *PlgHttpWsServ) ReloadConf(conf *wrapper.SuperValue) error {

	if this.wsservice == nil {
		this.wsservice = PrjHttpWs.NewWsHttpServiceHandleEx(gohttp.HttpHandle, gohttp.UnHandle)
	}

	if this.monitor_send == nil {
		this.monitor_send = utils.NewMonitorSpeedSizeRec()
		this.monitor_recv = utils.NewMonitorSpeedSizeRec()
		utils.Monitor.AddMonitorRec(this.monitor_send, this.monitor_send)
		utils.Monitor.AddMonitorRec(this.monitor_recv, this.monitor_recv)
		this.wsservice.ConfigMonitor(this.monitor_send, this.monitor_recv)
	}

	conf.CheckStrFunc("wsurl", func(strv string) {
		if this.wsurl != strv {
			this.wsservice.ConfigServiceUrl(strv)
			this.wsurl = strv
		}
	})

	return nil
}

func (this *PlgHttpWsServ) OnHttpStatus(rec *PlgHttpRec) (rval interface{}, errcode int, err error) {
	json := wrapper.NewSVObject()
	json.SetKeyValues("send-info", this.monitor_send.Info(), "recv-info", this.monitor_recv.Info(),
		"online", this.wsservice.Online(), "ws-url", this.wsurl,
		"ws-ex-status", this.wsservice.ExStatus(),
	)
	PrjHttpUtils.JSON2TableRec(rec.RespW, "", json.AsJSONString(false))
	return
}

func (this *PlgHttpWsServ) OnObjectNotify(sender interface{}, notifytype int, data interface{}) (rval interface{}, err error) {
	if notifytype == utils.NOTIFY_TYPE_SETCONF {
		if conf, ok := data.(*wrapper.SuperValue); ok {
			err = this.ReloadConf(conf)
		} else {
			err = fmt.Errorf("非法的JSON配置")
		}
	} else if notifytype == utils.NOTIFY_TYPE_RELEASE {
		if this.wsservice != nil {
			this.wsservice.Close()
		}
	}
	return
}

func CreatePlgHttpWsServFunc(args ...interface{}) (rval interface{}, err error) {
	obj := &PlgHttpWsServ{}
	if len(args) > 0 {
		if str, ok := args[0].(string); ok {
			obj.plugId = str
		}
	}
	rval = obj
	return
}
